<?php

class OneStopControllerSendMail extends JController
{
	function request()
	{
		$post = JRequest::get('post');
		
		$session = JFactory::getSession();
		$captcha = $session->get('kcaptcha');
		
		if($post['captcha'] != $captcha)
		{
			
			$link = JRoute::_('index.php?option=com_onestop&view='.$post['mail']);
			$this->setRedirect($link, 'Security code is invalid.', 'notice');
			
			return;
		}
		
		//upload file
		$files = JRequest::get('files');
		
		$target_path = null;
		
		if(isset($files['uploadedfile']['name']) && $files['uploadedfile']['name'])
		{			
			$target_path = JPATH_ROOT . "/tmp/";
	
			$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 
			
			if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
			{
			    $msg = "There was an error uploading the file, please try again!";
			    
			    $link = JRoute::_('index.php?option=com_onestop&view='.$post['mail'], false);
				$this->setRedirect($link, $msg, 'notice');
				
				return;
			}
		}
		
		$requestView = $this->getView('Mail', 'html', 'OneStopView');
		
		if($post['mail'] == 'request')
		{
			$subject = 'Request Email';			
			$body = $requestView->loadTemplate('request');
		}
		if($post['mail'] == 'work_with_us')
		{
			$subject = 'Job';			
			$body = $requestView->loadTemplate('work_with_us');
		}
		else 
		{
			$subject = 'Quote Email';			
			$body = $requestView->loadTemplate('quote');
		}
		
		$email = $this->sendEmail($subject, $body, $target_path);
		
		if($email == 'SEND_MAIL_OK')
		{
			$link = JRoute::_('index.php?option=com_onestop&view=finish&mail='.$post['mail']);
			$this->setRedirect($link, 'Email Sent', 'message');
		}
		else 
		{
			$link = JRoute::_('index.php?option=com_onestop&view='.$post['mail']);
			$this->setRedirect($link, $email, 'notice');
		}
		
		return;
	}
	
	function sendEmail($subject, $body, $fileAttach = null)
	{
		$mailer =& JFactory::getMailer();
		
		$config =& JFactory::getConfig();
		$sender = array( 
						$config->getValue( 'config.mailfrom' ),
						$config->getValue( 'config.fromname' ) 
					);
		
		//set sender
		$mailer->setSender($sender);
		
		//set receiver
		$mailer->addRecipient( $config->getValue( 'config.mailfrom') );
		$mailer->addRecipient( 'nguyenxuanmui@gmail.com' );
		
		$mailer->isHTML(true);
		$mailer->Encoding = 'base64';
		
		//set subject
		$mailer->setSubject($config->getValue( 'config.sitename' ) . ': ' .$subject);
		
		//set mail body
		$mailer->setBody($body);
		
		if($fileAttach)
			$mailer->addAttachment($fileAttach);
		
		//send email
		$send =& $mailer->Send();
		if ( $send !== true )
			return false;
		else
			return 'SEND_MAIL_OK';
	}
}